package com.roubsite.sso.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;

import com.roubsite.admin.dao.user.IUserDao;
import com.roubsite.admin.dao.user.UserDao;
import com.roubsite.database.annotation.Dao;
import com.roubsite.security.securityInfo.RSSecurityBaseUserInfo;
import com.roubsite.security.securityInfo.RSUserInfo;
import com.roubsite.security.utils.RSPasswordUtil;
import com.roubsite.security.utils.RSSecurityUtils;
import com.roubsite.sso.dao.ISsoDao;
import com.roubsite.sso.utils.SignData;
import com.roubsite.utils.JsonUtils;
import com.roubsite.utils.StringUtils;
import com.roubsite.web.action.RSAction;

/**
 * sso单点登录 状态码 status：200接口请求成功；403接口未授权
 * 
 * @author lones
 *
 */
public class IndexAction extends RSAction {
	private static SignData sd = new SignData();
	@Dao(impl = UserDao.class, dataSource = "dataSource")
	IUserDao userDao;
	@Dao(impl = UserDao.class, dataSource = "dataSource")
	ISsoDao ssoDao;

	@Override
	public void execute() throws Exception {

	}

	/**
	 * 登录页面
	 * 
	 * @throws ServletException
	 * @throws IOException
	 */
	public void doSsoLogin() throws ServletException, IOException {
		String redirectUri = (String) this.s("redirectUri");
		if (StringUtils.isEmpty(redirectUri)) {
			redirectUri = request.getContextPath();
		}
		String systemId = this.$_G("system_id");
		this.assign("systemId", systemId);
		this.assign("redirectUri", redirectUri);
		this.getSession().setAttribute("redirectUri", redirectUri);
		this.display("ssoLogin.html");
	}

	/**
	 * 登陆方法（1：登陆成功。-2：密码错误。-1:没有该用户。-3:验证码错误）
	 */
	public void doSsoLoginRequest() throws Exception {
		Map<String, Object> ret = new HashMap<>();
		String username = (String) this.$_P("username");
		String pwd = (String) this.$_P("pwd");
		String verifyImgCode = (String) this.$_P("verifyImg");
		String vvv = "";
		ret.put("status", 0);
		if (StringUtils.isNotEmptyObject(this.s("verifyImg"))) {
			vvv = (String) this.s("verifyImg");
		}
		vvv = vvv.toLowerCase();
		if (!verifyImgCode.toLowerCase().equals(vvv) || StringUtils.isEmpty(vvv)) {
			ret.put("status", -3);
		} else {
			Map map = userDao.getUserInfo(username);
			if (null != map) {
				String passwd = (String) map.get("USER_PASSWORD");
				if (new RSPasswordUtil().matches(pwd, passwd)) {
					// 登陆成功
					RSSecurityBaseUserInfo userInfo = new RSSecurityBaseUserInfo();
					// 用户信息
					userInfo.setUid((String) map.get("USER_ID"));
					userInfo.setUserName(username);
					userInfo.setUserStatus((String) map.get("USER_STATUS"));
					// 用户组织信息
					userInfo.setOrganId((String) map.get("ORGAN_ID"));
					userInfo.setOrganCode((String) map.get("ORGAN_CODE"));
					userInfo.setOrganName((String) map.get("ORGAN_NAME"));
					userInfo.setOrganType((String) map.get("ORGAN_TYPE"));
					userInfo.setOrganParentId((String) map.get("PARENT_ID"));
					// 用户权限信息
					userInfo.setRoleIds(userDao.getUserRoles((String) map.get("USER_ID")));
					RSSecurityUtils.login(getSession(), userInfo);
					ret.put("status", 1);

				} else {
					// 登陆失败
					ret.put("status", -2);
				}
			} else {
				// 没有找到该用户
				ret.put("status", -1);
			}
		}
		this.getSession().setAttribute("verifyImg", "");
		this.print(JsonUtils.convertToString(ret));
	}

	public void doSsoMessage() throws ServletException, IOException {
		String systemId = this.$_G("system_id");
		String redirectUri = this.$_G("redirect_uri");
		String sign = this.$_G("sign");

		this.assign("systemId", systemId);
		this.assign("redirectUri", redirectUri);
		this.assign("sign", sign);
		this.display("ssoMessage.html");

	}

	/**
	 * 获取业务系统CODE和用户的ACCESS_TOKEN
	 * 
	 * @接收参数（get方式）system_id;redirect_uri
	 * @限制：1、返回的code有效期10分钟；2、返回code有效调用次数1次
	 * @数据签名：code+token进行签名
	 * @throws Exception
	 * @return status：403--没有权限，200--正常
	 */
	public void doGetAuthorizationCode() throws Exception {
		Map<String, Object> retMap = new HashMap<>();
		retMap.put("status", 403);
		String systemId = this.$_G("system_id");
		String redirectUri = this.$_G("redirect_uri");
		String sign = this.$_G("sign");
		if (!sd.verifyWhole(systemId + redirectUri, sign)) {
			this.print(JsonUtils.convertToString(retMap));
			return;
		}
		// 判断用户是否登录
		RSSecurityBaseUserInfo rsSecUserInfo = (RSSecurityBaseUserInfo) getSession().getAttribute("rsSecUserInfo");
		RSUserInfo rSUserInfo = new RSUserInfo(rsSecUserInfo);
		if (StringUtils.isNotEmpty(rSUserInfo.getUid())) {
			// 用户已经登录则直接可以返回认证数据
			String code = ssoDao.getSystemCode(systemId);
			String token = ssoDao.getUserToken(systemId, rSUserInfo.getUid());
			String sign1 = sd.signWhole(code + token);
			retMap.put("status", 200);
			retMap.put("code", code);
			retMap.put("access_token", token);
			retMap.put("sign", sign1);
			if (redirectUri.indexOf("?") > 0) {
				redirectUri = redirectUri + "&status=200&code=" + code + "access_token=" + token + "&sign" + sign1;
			} else {
				redirectUri = redirectUri + "?status=200&code=" + code + "access_token=" + token + "&sign" + sign1;
			}
			System.out.println(JsonUtils.convertToString(retMap));
			this.response.sendRedirect(redirectUri);

		} else {
			this.response.sendRedirect(request.getContextPath() + "/sso/index/ssoLogin?system_id=" + systemId
					+ "&redirect_uri=" + redirectUri + "&sign=" + sign);
			return;
		}
	}

	/**
	 * 获取用户信息
	 * 
	 * @throws Exception
	 */
	public void doGetUserInfo() throws Exception {
		Map ret = new HashMap<>();
		String token = this.$_G("access_token");
		String code = this.$_G("code");
		String systemId = this.$_G("system_id");
		String sign = this.$_G("sign");
		if (!sd.verifyWhole(token + code + systemId, sign)) {
			ret.put("status", "404");
			this.print(JsonUtils.convertToString(ret));
			return;
		}
		if (ssoDao.checkCode(code, systemId)) {
			Map m = ssoDao.getUserInfoByToken(token);
			ret.putAll(m);
			ret.put("status", "200");
		} else {
			ret.put("status", "404");
			ret.put("message", "code错误");
		}
		this.print(JsonUtils.convertToString(ret));
	}
}
